package com.hmall.cart.listener;

import cn.hutool.json.JSONUtil;
import com.hmall.cart.service.ICartService;
import com.hmall.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class CartClearListener {
    private final ICartService cartService;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "cart.clear.queue", durable = "true"),
            exchange = @Exchange(name = "trade.topic"),
            key = "order.create"
    ))
    public void listenOrderCreate(@Payload String itemIds/*, @Header("userId")Long userId*/){
        Long userId = UserContext.getUser();
        log.info("订单已创建，正在清理用户号为：{}的购物车",userId);
        //UserContext.setUser(userId);
        List<Long> IdsList = JSONUtil.toList(itemIds, Long.class);
        cartService.removeByItemIds(IdsList);
    }
}
